package com.magnate.software.mongo.db.interceptor;

import com.magnate.software.common.utils.StringUtils;
import com.magnate.software.mongo.db.context.PagingContextHolder;
import com.magnate.software.mongo.db.domain.Page;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;

/**
 * mongodb翻页拦截器
 *
 * @author WangYang
 * @version 1.0
 * @datetime 2016/11/30 15:55
 */
@Service("mongoTemplatePageInterceptor")
public class MongoTemplatePageInterceptor implements MethodInterceptor, ApplicationContextAware {

    private MongoTemplate mongoTemplate;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        mongoTemplate = (MongoTemplate) applicationContext.getBean("mongoTemplate");
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        // 翻页参数
        Page page = PagingContextHolder.getPage();
        // 方法
        Method method = invocation.getMethod();
        String methodName = method.getName();
        if (page != null && StringUtils.isNotBlank(methodName) && methodName.equals("find")) {
            Object[] args = invocation.getArguments();

            Query query = (Query) args[0];

            long count = mongoTemplate.count(query, (Class) args[1]);
            page.setTotalResult(count);

            System.out.println(count);

            query.limit((int) page.getPageSize());
            query.skip((int) (page.getCurrentPage() * page.getPageSize()));
            args[0] = query;
        }
        return invocation.proceed();
    }

}
